<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="设备编号" prop="deviceId">
            <el-input v-model="queryParams.deviceId" placeholder="请输入设备编号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="定位状态" prop="gpsStatus">
            <el-select v-model="queryParams.gpsStatus" placeholder="请选择定位状态" clearable>
              <el-option v-for="dict in gps_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="铁轨" prop="track">
            <el-checkbox v-model="queryParams.track" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="车轮" prop="wheel">
            <el-checkbox v-model="queryParams.wheel" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['zntx-app:device:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['zntx-app:device:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['zntx-app:device:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['zntx-app:device:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="" align="center" prop="id" v-if="true" /> -->
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="设备编号" align="center" prop="deviceId" />
        <el-table-column label="所属工位" align="center" prop="regionName" />
        <el-table-column label="设备状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="device_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="定位状态" align="center" prop="gpsStatus">-->
        <!--          <template #default="scope">-->
        <!--            <dict-tag :options="gps_status" :value="scope.row.gpsStatus" />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="GPS定位">
          <template #default="scope">
            <el-popover v-if="scope.row.latitude>1" placement="bottom" title="位置" :width="200" trigger="click">
              <template #reference>
                <el-button type="primary" text class="m-2">查看</el-button>
              </template>
              <div>
                经度: {{ scope.row.longtitude }}<br />
                纬度：{{ scope.row.latitude }}
              </div>
            </el-popover>
            <span v-else>/</span>
          </template>
        </el-table-column>
        <el-table-column label="电量" align="center" prop="energy">
          <template #default="scope">
            <span v-if="scope.row.energy">{{ scope.row.energy }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="姿态" align="center" prop="posX">
          <template #default="scope">
            <span v-if="scope.row.posX > 0">运动</span>
            <span v-else>静止</span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="姿态-Y" align="center" prop="posY" />-->
        <!--        <el-table-column label="姿态-Z" align="center" prop="posZ" />-->
        <el-table-column label="RFID" align="center" prop="rfid" />
        <el-table-column label="铁轨" align="center" prop="track">
          <template #default="scope">
            <span>{{ scope.row.track?'是':'否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车轮" align="center" prop="wheel">
          <template #default="scope">
            <span>{{ scope.row.wheel?'是':'否' }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="rfid标签" align="center" prop="rfid" />-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template #default="scope">
            <el-button link type="primary" @click="handleShowRecord(scope.row)" v-hasPermi="['zntx-app:device:edit']">历史状态</el-button>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['zntx-app:device:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['zntx-app:device:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改智能铁鞋对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="deviceFormRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="RFID标签" prop="rfid">
          <el-input v-model="form.rfid" placeholder="请输入RFID标签" />
        </el-form-item>
        <el-form-item label="所属工位" prop="region">
          <el-select v-model="form.region" placeholder="请选择工位">
            <el-option v-for="item in regions" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in device_status" :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="经度" prop="longtitude">
          <el-input v-model="form.longtitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="电量" prop="energy">
          <el-input v-model="form.energy" placeholder="请输入电量" />
        </el-form-item>
        <el-form-item label="姿态-X" prop="posX">
          <el-input v-model="form.posX" placeholder="请输入姿态-X" />
        </el-form-item>
        <el-form-item label="姿态-Y" prop="posY">
          <el-input v-model="form.posY" placeholder="请输入姿态-Y" />
        </el-form-item>
        <el-form-item label="姿态-Z" prop="posZ">
          <el-input v-model="form.posZ" placeholder="请输入姿态-Z" />
        </el-form-item>
        <el-form-item label="加速度" prop="accelerate">
          <el-input v-model="form.accelerate" placeholder="请输入加速度" />
        </el-form-item>
        <el-form-item label="铁轨贴实" prop="track">
          <el-input v-model="form.track" placeholder="请输入铁轨贴实" />
        </el-form-item>
        <el-form-item label="车轮" prop="wheel">
          <el-input v-model="form.wheel" placeholder="请输入车轮" />
        </el-form-item> -->
        <!-- <el-form-item label="rfid标签" prop="rfid">
          <el-input v-model="form.rfid" placeholder="请输入rfid标签" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer size="50%" v-model="drawer" title="铁鞋历史状态" :direction="direction">
      <el-form :model="queryHisParams" ref="queryHisFormRef" :inline="true" label-width="68px">
        <el-form-item label="时间">
          <el-date-picker
            v-model="queryHisParams.timespan"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            clearable
            style="width: 380px"
            @keyup.enter="handleQueryHis"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQueryHis">搜索</el-button>
          <el-button @click="handleQueryHisReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loadingHis" :data="deviceRecords">
        <el-table-column label="定位状态" align="center" prop="gpsStatus">
          <template #default="scope">
            <dict-tag :options="gps_status" :value="scope.row.gpsStatus" />
          </template>
        </el-table-column>
        <el-table-column label="GPS定位">
          <template #default="scope">
            <span v-if="scope.row.latitude">{{ scope.row.latitude }};{{ scope.row.longtitude }}</span>
          </template>
        </el-table-column>
        <el-table-column label="电量" align="center" prop="energy" />
        <el-table-column label="姿态" align="center">
          <template #default="scope">
            <span v-if="scope.row.posX > 0">运动</span>
            <span v-else>静止</span>
          </template>
        </el-table-column>
        <el-table-column label="铁轨贴实" align="center" prop="track">
          <template #default="scope">
            <span>{{ scope.row.track?'是':'否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车轮" align="center" prop="wheel">
          <template #default="scope">
            <span>{{ scope.row.wheel?'是':'否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="rfid标签" align="center" prop="rfid">
          <template #default="scope">
            <span>{{ scope.row.rfid?scope.row.rfid:"未检测到" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时间" align="center" prop="createTime" />
      </el-table>
    </el-drawer>
  </div>
</template>

<script setup name="Device" lang="ts">
import { ElMessageBox } from 'element-plus'
import type { DrawerProps } from 'element-plus'
import { listDevice, getDevice, delDevice, addDevice, updateDevice } from '@/api/zntx-app/device';
import { DeviceVO, DeviceQuery, DeviceForm } from '@/api/zntx-app/device/types';
import { DeviceHistoryQuery, DeviceHistoryVO } from '@/api/zntx-app/deviceHistory/types';
import { listDeviceHistory } from '@/api/zntx-app/deviceHistory';
import {RegionVO} from "@/api/zntx-app/region/types";
import {listRegion} from "@/api/zntx-app/region";
const drawer = ref(false);
const direction = ref<DrawerProps['direction']>('rtl');
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('Are you sure you want to close this?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { device_status } = toRefs<any>(proxy?.useDict('device_status'));
const { gps_status } = toRefs<any>(proxy?.useDict('gps_status'));
const deviceRecords=ref<DeviceHistoryVO[]>([]);
const deviceList = ref<DeviceVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const loadingHis = ref(false);
const hisTotal = ref(0);
const queryHisParams = ref<DeviceHistoryQuery>({
  pageNum:1,
  pageSize: 20
});
const queryFormRef = ref<ElFormInstance>();
const deviceFormRef = ref<ElFormInstance>();
const regions = ref<RegionVO[]>([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: DeviceForm = {
  id: undefined,
  deviceId: undefined,
  status: undefined,
  latitude: undefined,
  longtitude: undefined,
  energy: undefined,
  posX: undefined,
  posY: undefined,
  posZ: undefined,
  accelerate: undefined,
  track: undefined,
  wheel: undefined,
  rfid: undefined,
  deviceName: undefined
}
const data = reactive<PageData<DeviceForm, DeviceQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceId: undefined,
    deviceName: undefined,
    track: undefined,
    wheel: undefined,
    gpsStatus: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    deviceName: [
      { required: true, message: "设备名称不能为空", trigger: "blur" }
    ],
    deviceId: [
      { required: true, message: "设备编号不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "设备状态不能为空", trigger: "change" }
    ],
    rfid: [
      { required: true, message: "RFID编号不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);
const loadRegions = async()=>{
  const res = await listRegion();
  console.log('regions', res)
  regions.value = res.rows;
};
/** 查询智能铁鞋列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDevice(queryParams.value);
  deviceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  deviceFormRef.value?.resetFields();
  loadRegions();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

const handleShowRecord = (row?:DeviceVO) => {
  drawer.value = true;
  if(queryHisParams.value){
    queryHisParams.value.deviceId = row?.deviceId;
  }
  handleQueryHis();
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

const handleQueryHis = async() => {
  loadingHis.value = true;
  const res = await listDeviceHistory(queryHisParams.value);
  console.log("his", res)
  deviceRecords.value = res.rows;
  hisTotal.value = res.total;
  loadingHis.value = false;
}

const handleQueryHisReset = ()=>{
  if(queryHisParams.value){
    queryHisParams.value.timespan = undefined;
  }
  handleQueryHis();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: DeviceVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加智能铁鞋";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: DeviceVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getDevice(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改智能铁鞋";
}

/** 提交按钮 */
const submitForm = () => {
  deviceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateDevice(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addDevice(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: DeviceVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除智能铁鞋编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delDevice(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('zntx-app/device/export', {
    ...queryParams.value
  }, `device_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
